<?php 
$peer = OrdersPeer::getInstance();
$id = Zend_Controller_Front::getInstance()->getRequest()->getParam('id');
$order = $peer->find($id)->current();
if (!$order) $order = OrdersPeer::getInstance()->createRow();


$form = $this->element;

// payment method
$payment = $form->getElement('payment_method_id');
$default = PaymentMethodsPeer::getInstance()->findByKey('cash')->current();
if (!$payment->getValue()) {
	$payment->setValue($default->getId());
}

$current = $payment->getValue();
foreach ($payment->getMultiOptions() as $key => $value) {
	if ($key != $current) $payment->removeMultiOption($key);
}

// type
$type = $form->getElement('type_id');
$type->setLabel(null);
$type->setDecorators(array('ViewHelper'));
$default = OrderTypePeer::getInstance()->fetchByKey('operator');
if (!$type->getValue()) {
	$type->setValue($default->getId());
}

$current = $type->getValue();
foreach ($type->getMultiOptions() as $key => $value) {
	if ($key != $current) $type->removeMultiOption($key);
}
$type->setAttrib('style', 'display:none;');

// delivery_time
$deliveryTime = $form->getElement('delivery_time_id');
if (!$order->getId()) {
	$options = $deliveryTime->getMultiOptions();
	$deliveryTime->clearMultiOptions();
	$deliveryTime->addMultiOption(null);
	$deliveryTime->addMultiOptions($options);
}


$elements = $form->getElements();
foreach ($elements as $key => $element) {
	if ($element->class == 'wysiwyg' || $element->class == 'map') {
		$element->class = '';
	}
	
}
foreach (array(
	'operator_id', 
	'executed_at', 
	'delivery_time_id', 
	'payment_method_id',
	) as $element) {
		$el = $form->$element;
		$el->removeDecorator("HtmlTag");
		$el->getDecorator("Label")->setTag(null);
}

if (!$order->isModifiedAvailable()) {
	foreach ($form->getElements() as $element) {
		if ($element->class == 'date') $element->class = '';
		$element->setAttrib('readonly', 'readonly');
	}
}

?>

<style media="screen" type="text/css">
    .defaultText { width: 100px; }
    .defaultTextActive { color: #a1a1a1; font-style: italic; }
    fieldset { padding:10px; }
    fieldset legend { font-size:14px; font-weight:bold; color:gray; }
    .orderedit td { padding:4px; }
    .orderedit thead,.orderedit tfoot { font-size:14px; font-weight:bold;}
    .listorder { border-right:1px solid gray; border-bottom:1px solid gray; }
    .orderedit .td1 { text-align:left; width:50%; border-left:1px solid gray; border-top:1px solid gray;}
    .orderedit .td2 { text-align:center; width:10%; border-left:1px solid gray; border-top:1px solid gray;}
    .orderedit label { font-weight:bold; }
    .comment { padding:10px; border-left:1px dashed gray; margin-bottom:10px; }
</style>

<form action="" method="post" id="form_cc">

	<?php echo $form->type_id; ?>
    <h2>
    	<?php 
    		if ($order->getId()) {
    			echo "Заказ №{$order->getId()}";
    			$timestamp = strtotime($order->getCreatedAt()); 
    			echo ' от ' . date("d F Y (H:i)", $timestamp);
    		} else {
    			echo "Новый заказ";
    		}
    	?>
    </h2>
    <?php

    if ($order->getId()) {
    	$statusRow = $order->getOrderStatusRowByOrderStatusId();
    	echo "<h3>Статус: {$statusRow->getName()}</h3>";
    }
    ?>
    <br />
    <?php 
	$delivery = $order->getDeliveryRowByDeliveryId();
	if (!$delivery) {
		$delivery = DeliveryPeer::getInstance()->createRow();
	}

	// Show logs
	if ($order->getId()) {
    	$rowset = $order->getOrderLogRowsetByOrderId();
    	if ($rowset->count()) {
	    	echo '<p class="comment">';
		    foreach ($rowset as $row) {
		    	$message = $row->getMessage();
				$userId = $row->getAdminUserId();
		    	$user = AdminUserPeer::getInstance()->find($userId)->current();
		    	$name = $user->getName() ? $user->getName() : $user->getLogin();
		    	
		    	$message = sprintf($message, $name);
		    	
		   		$time = strtotime($row->getCreated());
		   		$time = date("d.m.Y в H:i", $time);
		   		echo "[$time] $message<br />";
		    }
		    echo '</p>';
    	}
    }

    /**
     * Translate some form errrors.
     * 
     * @param string $key
     * @param string $error
     * @return string
     */
    function _translate($key, $error)
    {
    	$_translated = array(
			'isEmpty' => 'Поле обязательно для заполнения',
		);
	
    	if (isset($_translated[$key])) {
    		return $_translated[$key];
    	}
    	
    	return $error;
    }
    
    $errors = $form->getMessages();
    foreach ($errors as $key => $error) {
    	if (is_array($error)) {
    		unset($errors[$key]);
    	}

   		if (is_array($error)) {
     		foreach ($error as $k => $v) {
     			$label = $form->getElement($key)->getLabel();
     			$v = _translate($k, $v);
     			$errors[$key][$k] = "$label -- $v";
     		}
    	} else {
    		$errors[$key] = _translate($key, $error);
    	}
    }

    if ($errors) {
	    echo "<ul class='errors'>";
	    foreach ($errors as $error) {
	    	if (is_array($error)) {
	    		foreach ($error as $k => $v) {
	    			echo "<li>$v</li>";
	    		}
	    	} else {
	    		echo "<li>$error</li>";
	    	}
	    }
	    echo "</ul>";
    }
    ?>
    <fieldset>
	<legend>Изменение цен
	 <div class="type_script" style="margin-bottom: 30px; font-weight:bold; ">
				<input class='percent' style="display: block; float: left; margin-top: 1px; margin-right: 3px;" type="radio" name="type_script" value="percent">
				<lable>Процент</lable>
		        <div class="clear"></div>
				<input class="price_product" style="display: block; float: left; margin-top: 1px; margin-right: 3px;" type="radio" name="type_script" value="price_product">
		        <lable>Цена продукта</lable>
		        <!--<div class="clear"></div>
				<input class="delivery_sum" style="display: block; float: left; margin-top: 1px; margin-right: 3px;" type="radio" name="type_script" value="delivery_sum">
		        <lable>Сумма доставки</lable>
				</div>-->
		<script type="text/javascript">


			$(document).ready(function(){
			var clean_price_count = $('input[name^=clean]').length;
			var i = 0;
			var b = 0;
			for(i = 0; clean_price_count > i; i++){
				var val_clean = $('input[name=clean_price_'+i+']').val();
				val_clean = parseInt(val_clean);
				var val_price = $('input[name=no_percent_'+i+']').val();
				//alert(val_clean + '/' + val_price);
				if(val_clean != val_price){
					b = b + 1;
				}
			}
				if(!$('.price_product').is(':checked') && !$('.percent').is(':checked'))
				{
					$('#percent').attr('readonly', 'readonly').css('background','#EEE');
					$('input[for="input_price"]').attr('readonly', 'readonly').css('background','#EEE');
				}
			//если были изменены цены хоть одного продукта
			if(b > 0){
				$('.price_product').attr('checked','checked');
				$('#percent').attr('readonly', 'readonly').css('background','#EEE');
				$('input[for="input_price"]').attr('readonly', '').css('background','#FFF');
			}

			var percent = $('#percent').val();
			if(percent > 0){
				$('.percent').attr('checked','checked');
				$('input[for="input_price"]').attr('readonly', 'readonly').css('background','#EEE');
				$('#percent').attr('readonly', '').css('background','#FFF');
			}
			});


			$('.type_script > input').click(function(){
				var ee = $(this).val();

				if(ee == 'percent'){

					$('input[for="input_price"]').attr('readonly', 'readonly').css('background','#EEE');
					$('#percent').attr('readonly', '').css('background','#FFF');					
				}

				if(ee == 'price_product'){
					$('#percent').attr('readonly', 'readonly').css('background','#EEE');
					$('input[for="input_price"]').attr('readonly', '').css('background','#FFF');
				}


			});

		</script>
	<table id="percent_summ" cellpadding="0" cellspacing="0" border="0" class="orderedit">
	    <tr>
		    <td>
				<?php
				$input = new Zend_Form_Element_Text('total');
				$input->setLabel('Сумма заказа:');
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $order->getTotalCost());
				$input->setValue($order->getTotalCost());
				$input->setAttrib('readonly', 'readonly');
				$input->setAttrib('style', 'background: #EEE;');
				echo $input;
				?>
			</td>

				<td>
				<?php
				$input = new Zend_Form_Element_Text('percent');
				$input->setLabel('Процент на скидку:');
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $order->getPercent());
				$input->setAttrib('id', 'percent');
				if (!$order->isModifiedAvailable()) {
					$input->setAttrib('readonly', 'readonly');
				}
				echo $input;
					
				?>
			</td>
			
		</tr>
		</table>
				<?php
				$id = Zend_Controller_Front::getInstance()->getRequest()->getParam('id');
				if(isset($id)){
				$price_order = Order2productPeer::getInstance();
				//$id = Zend_Controller_Front::getInstance()->getRequest()->getParam('id');
				$select = Order2productPeer::getInstance()->select();
				$select->setIntegrityCheck(false);
				$select->join('product', 'product.id = order2product.product_id', 'name');
				$select->where('`order_id` = ?', $id);
				$order_price = $price_order->fetchAll($select);
				}
				?>
	<table id="list_product_price">

				<?php $i = 0; $b = 0; if(isset($id) && count($order_price) > 0){
					foreach($order_price as $price){
						if($price['clean_price'] == null || $price['clean_price'] == 0 || $price['clean_price'] == 0.00){
							$p_o = Order2productPeer::getInstance();
							$data = array(
								'clean_price' => $price['price']
							);
							$p_o->update($data, 'id ='.$price['id']);
							$b++;
						}
						if($b > 0){
							echo "<script>document.location.reload();</script>";							
						}
					echo '<tr>';
 					echo "<td><lable>".$price['name'].
							 "</lable><br><strong>Цена по умолчанию: </strong><input style='background: #EEE;' readonly='readonly' name='clean_price_".$i.
							 "' value='".$price['clean_price']."'><input type='hidden' name='price_id_".$i.
							 "' value=".$price['product_id'].
							 "><strong style='margin-left: 10px;'>Цена: </strong><input for='input_price' name='no_percent_".$i.
							 "' value='".$price['price']."'><input for='input_price' type='hidden' name='no_percent_count_".$i.
							 "' value='".$price['count']."'><br><br></td>";
					echo '</tr>';
					$i++;
				}
			}
				?>
				<tr><td>
				<br>
				<?php
				$input = new Zend_Form_Element_Text('delivery_sum');
				$input->setLabel('Стоимость доставки:');
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $order->getDeliveryCost());
				$input->setValue((int)$order->getDeliveryCost());
				echo $input;
				?>
			</td></tr>
				<tr><td>
				<br>
				<?php
				$input = new Zend_Form_Element_Text('total_price');
				//$input->setLabel('Сумма по умолчанию:');
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $order->getTotalPrice());

				if($order->getTotalPrice() == 0 || $order->getTotalPrice() == null || $order->getTotalPrice() == 0.00){
					$input->setValue($order->getTotalCost());
				}else{
					$input->setValue($order->getTotalPrice());
				}

				$input->setAttrib('readonly', 'readonly');
				$input->setAttrib('style', 'display: none;');
				echo $input;
				?>
			</td></tr>
		</table>
	</legend>
		
    </fieldset>
    <fieldset>
<script>
$(function() {
	$("#create_user").click(function() {
		var $email = $("#email");
		if (!$email.val()) {
			alert('Заполните хотя бы электронный адрес для создания нового пользователя');
			return false;
		}

		var $columns = [
			'email', 
			'firstName', 
			'lastName', 
			'phone', 
			'suggest_city', 
			'suggest_street', 
			'home', 
			'corps', 
			'porch', 
			'level',
			'flat'
		]

		var $data = '';
		for (var $key in $columns) {
			var $column = $columns[$key];
			var $value = $("#" + $column).val();
			
			$data += $column + '=' + $value + '&';
		}

		$.ajax({
			url: '/admin/call-center/create-user/orderId/<?php echo $id; ?>',
			type: 'post',
			data: $data,
			dataType: 'json',
			success: function($data) {
				if ($data.result == 'failure') {
					alert($data.message);
					return false;
				}

				$("#create_user").remove();
				$("#is_registered").text("Да");
				alert('Пользователь создан');
				return false;
			}
		});

		return false;
	});
});
</script>

<?php 
$registered = 0;
        	$profile = $order->getProfileRowByProfileId();
        	if ($profile) {
        		$email = $profile->getEmail();
        		if (($email == 'h@detmir.ru') || ($email == 'frontend@detmir.ru')) {
        			$registered = 0;
        		} else {
        			$registered = 1;
        		}
        	} else {
        		$registered = 0;
        	}
?>
            
	<legend>Информация о клиенте 

	</legend>
	<table cellpadding="0" cellspacing="0" border="0" class="orderedit">
	    <tr>
			<td>
				<?php 
				$input = new Zend_Form_Element_Text('firstName');
				$input->setLabel('Имя:');
				$input->setRequired(1);
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $delivery->getFirstName());
				$input->setValue($delivery->getFirstName());
				if (!$order->isModifiedAvailable()) {
					$input->setAttrib('readonly', 'readonly');
				}
				
				echo $input;
				?>
			</td>
			<td>
				<?php 
				$input = new Zend_Form_Element_Text('lastName');
				$input->setLabel('Фамилия:');
				$input->setRequired(1);
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $delivery->getLastName());
				$input->setValue($delivery->getLastName());
				if (!$order->isModifiedAvailable()) {
					$input->setAttrib('readonly', 'readonly');
				}
				
				echo $input;
				?>
			</td>
			<td>
				<?php 
				$input = new Zend_Form_Element_Text('email');
				$input->setLabel('Email:');
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $delivery->getEmail());
				if (!$order->isModifiedAvailable()) {
					$input->setAttrib('readonly', 'readonly');
				}
				
				echo $input;
				?>
			</td>
			<td>
				<?php
				$input = new Zend_Form_Element_Text('phone');
				$input->setLabel('Телефон:');
				$input->setRequired(1);
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $delivery->getPhone());
				$input->setValue($delivery->getPhone());
				if (!$order->isModifiedAvailable()) {
					$input->setAttrib('readonly', 'readonly');
				}

				echo $input;
				?>
			</td>
				<td>
				<?php
				$input = new Zend_Form_Element_Text('wikimart');
				$input->setLabel('Номер заказа викимарт:');
				//$input->setRequired(1);
				$input->setDecorators(array('ViewHelper', 'Label'));
				$input->setAttrib('default', $order->getWikimart());
				if (!$order->isModifiedAvailable()) {
					$input->setAttrib('readonly', 'readonly');
				}
				echo $input;
				?>
			</td>
	    </tr>
	    <tr>
		<td>
			<label>
				<a target="_blank" href='<?php echo $this->url(array('table' => 'profile', 'id' => null, 'action' => 'list')); ?>'>
					Найти пользователя
				</a>
			</label>
			<br />
            <label>Зарегистрирован: <span id='is_registered'>
            <?php 
            	echo ($registered) ? 'Да' : 'Нет';
            ?></span>
            </label>
            <br />
		    <label>Общее количество заказов:
		    <?php
		    		if ($profile) {
						$query = "select count(*) as count from orders where profile_id = {$profile->getId()}";
						$stmt = Db::getConnection()->query($query);
						$count = $stmt->fetchColumn();
						echo $count;
		    		} else {
		    			echo '-';
		    		}

		    ?></label>
        </td>
	    </tr>
	</table>
    </fieldset>
    <fieldset>
        <legend>Оплата</legend>

        <table cellpadding="0" cellspacing="0" border="0" class="orderedit">
            <tr>
                <td>
                    <?php 
                    $pm = $form->payment_method_id;
                    $payment = current($pm->getMultiOptions());
                    echo '<label>Способ оплаты:</label> ' . $payment;
                    if ($payment == 'Оплата картой') {
                    	echo "<font color='red'><b> (состав заказа менять нельзя)</b></font>";
                    }
                    $pm->setDecorators(array('ViewHelper'));
                    $pm->setAttrib('style', 'display:none;');
                    echo $pm; ?>
                </td>
				<td>&nbsp;
		    		
				</td>
            </tr>
        </table>
    </fieldset>
    <fieldset>
	<legend>Адрес доставки</legend>
	<table cellpadding="0" cellspacing="0" border="0" class="orderedit">
	    <tr>
		<td>
			<?php 
			$input = new Zend_Form_Element_Text('city');
			$input->setRequired(1);
			$input->setLabel('Город:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getCity());
			$input->setValue($delivery->getCity());

			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}

			$input->setAttrib('autocomplete', 'off');
			$input->setAttrib('id', 'suggest_city');
			$input->setAttrib('class', 'crud_form_suggest');

			$rel = '';
			if ($delivery->getCity()) {
				$city = CitiesPeer::getInstance()->findByName($delivery->getCity())->current();
				if ($city) {
					$rel = $city->getId();
				}
			}

			$input->setAttrib('rel', $rel);
			
			echo $input;
			?>
		    <div class="suggest_result" style="display:none;"></div>
		</td>
		<td>
			<?php 
			$input = new Zend_Form_Element_Text('street');
			$input->setRequired(1);
			$input->setLabel('Улица:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getStreet());
			$input->setValue($delivery->getStreet());
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}

			$input->setAttrib('autocomplete', 'off');
			$input->setAttrib('id', 'suggest_street');
			$input->setAttrib('class', 'crud_form_suggest');
			echo $input;
			?>
			<div class="suggest_result" style="display:none;"></div>
		</td>

		<td>
			<?php 
			$input = new Zend_Form_Element_Text('home');
			$input->setRequired(1);
			$input->setLabel('Дом:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getHome());
			$input->setValue($delivery->getHome());
			$input->setAttrib('style', 'width:50px;');
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}
			
			echo $input;
			?>
		</td>
		<td>
			<?php 
			$input = new Zend_Form_Element_Text('corps');
			$input->setLabel('Корпус:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getCorps());
			$input->setAttrib('style', 'width:30px;');
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}
			
			echo $input;
			?>
		</td>
		<td>
			<?php 
			$input = new Zend_Form_Element_Text('porch');
			$input->setLabel('Подъезд:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getPorch());
			$input->setAttrib('style', 'width:30px;');
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}
			
			echo $input;
			?>
		</td>
		<td>
			<?php 
			$input = new Zend_Form_Element_Text('level');
			$input->setLabel('Этаж:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getLevel());
			$input->setAttrib('style', 'width:30px;');
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}
			
			echo $input;
			?>
		</td>
		<td>
			<?php 
			$input = new Zend_Form_Element_Text('flat');
			$input->setLabel('Квартира:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			$input->setAttrib('default', $delivery->getFlat());
			$input->setAttrib('style', 'width:40px;');
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}
			
			echo $input;
			?>
		</td>
		<td>
			<?php 
			$input = new Zend_Form_Element_Select('metroId');
			$input->setLabel('Метро:');
			$input->setDecorators(array('ViewHelper', 'Label'));
			
			$mPeer = MetroPeer::getInstance();
			$mSelect = $mPeer->select();
			$mSelect->order('name');
			$mRowset = $mPeer->fetchAll($mSelect);
			$metros = array();
			foreach ($mRowset as $mRow) {
				$metros[$mRow->getId()] = $mRow->getName();
			}
			$input->addMultiOption(null);
			$input->addMultiOptions($metros);
			
			$input->setAttrib('default', $delivery->getMetroId());
			if (!$order->isModifiedAvailable()) {
				$input->setAttrib('readonly', 'readonly');
			}
			
			echo $input;
			?>
		</td>
	    </tr>
	    <tr>
		<td colspan="7">
		    <?php $form->delivery_comment->class = '';echo $form->delivery_comment; ?>
		</td>
	    </tr>

	</table>
    </fieldset>
    <fieldset>
	<legend>Логистический оператор</legend>
	<table cellpadding="0" cellspacing="0" border="0" class="orderedit">
	    <tr>
			<td>
				<label class="required" for="operator_id">Оператор</label>
				<select id="operator_id" name="operator_id">
				<option label="" value=""></option>
				<?php
			        $order_operator = DeliveryService::getInstance()->getActiveOperators();
					/* @var $operator OrderOperatorRow */
					foreach($order_operator as $operator)
					{
						if ($order->getOperatorId() == $operator->getId()) {
							echo '<option selected="selected" label="'.$operator->getName().'" value="'.$operator->getId().'">'.$operator->getName().'</option>';
						} else {
							echo '<option label="'.$operator->getName().'" value="'.$operator->getId().'">'.$operator->getName().'</option>';
						}
					}
			    ?>
				</select>
			    <?php //echo $form->operator_id; ?>
			</td>
			<td>
			    <?php
			    	$form->executed_at->class = '';
			    	echo $form->executed_at;
			    ?>
			</td>
			<td>
			    <?php echo $form->delivery_time_id; ?>
			</td>
			<td>
				<?php
					$input = new Zend_Form_Element_Checkbox('inMkad');
					$input->setLabel('В черте города?');
					$input->setDecorators(array('ViewHelper', 'Label'));
					$input->setAttrib('default', $delivery->getInMkad());
					if (!$order->isModifiedAvailable()) {
						$input->setAttrib('readonly', 'readonly');
					}

					if (($delivery->getCity() != 'Москва') && ($delivery->getCity() != 'москва')) {
						$input->setAttrib('disabled', 'disabled');
					}
					echo $input;
				?>
			</td>
	    </tr>
	</table>
    </fieldset>
    

	<?php 
	echo $this->render('call-center/_products_price.phtml');
	$deliveryCostElement = $form->getElement('delivery_cost');
   	$deliveryCostElement->setDecorators(array('ViewHelper'));
   	$deliveryCostElement->setAttrib('style', 'display:none;');
   	$deliveryCostElement->setAttrib('id', 'delivery_cost');
   	echo $deliveryCostElement;
	?>
	<br>
	<?php 
	$unverified = OrdersService::getInstance()->getOrderStatusByKey(OrdersService::STATUS_ORDER_UNVERIFIED);
	if ($order->isModifiedAvailable() || $order->getOrderStatusId() == $unverified->getId()) {
		if ($order->getId()) {
    		echo '<input name="submit" value="Оформить" type="submit" /> &nbsp; ';
		}
	}
	if ($order->getId()) {
		echo "<input name='exit' type='submit' value='Выйти из заказа' />";
	}
	?>
</form>
<style type="text/css">
p.comment label {
	display: block;
	font-weight: bold;
}
</style>